//
//  ZallFilterView.m
//  ZallDemo
//
//  Created by so on 16/6/20.
//  Copyright © 2016年 so. All rights reserved.
//

#import "ZallFilterView.h"
#import "NSObject+ZallAdditions.h"
#import "UIControl+ZallAddition.h"
#import "UIImageView+WebCache.h"

NSTimeInterval const ZallFilterAnimationDuration   = 0.3f;
static NSString * const CellReuseIdentifier = @"CellReuseIdentifier";

@interface ZallFilterView () {
    CGRect _preRect;
    CGRect _fromRect;
}
@property (strong, nonatomic, readonly) UIButton *maskButton;
@property (strong, nonatomic, readonly) UITableView *tableView;
@property (copy, nonatomic) NSArray <ZallFilterItem *> *items;
@end

@implementation ZallFilterView
@synthesize maskButton = _maskButton;
@synthesize tableView = _tableView;

#pragma mark - life cycle
- (void)dealloc {
    
}

- (instancetype)initWithFrame:(CGRect)frame items:(NSArray <__kindof ZallFilterItem *> * _Nonnull)items {
    self = [super initWithFrame:frame];
    if(self) {
        _preRect = frame;
        self.items = items;
        [self addSubview:self.tableView];
    }
    return (self);
}
#pragma mark -

#pragma mark - override
- (void)layoutSubviews {
    [super layoutSubviews];
    self.tableView.frame = UIEdgeInsetsInsetRect(self.bounds, self.contentInsets);
}
#pragma mark -

#pragma mark - setter
- (void)setRowHeight:(CGFloat)rowHeight {
    [self willChangeValueForKey:@"rowHeight"];
    self.tableView.rowHeight = rowHeight;
    [self didChangeValueForKey:@"rowHeight"];
    [self.tableView reloadData];
}

- (void)setDelegate:(id<ZallFilterViewDelegate>)delegate {
    [self willChangeValueForKey:@"delegate"];
    _delegate = delegate;
    [self didChangeValueForKey:@"delegate"];
    [self.tableView reloadData];
}
#pragma mark -

#pragma mark - getter
- (CGFloat)rowHeight {
    return (self.tableView.rowHeight);
}

- (UIButton *)maskButton {
    if(!_maskButton) {
        _maskButton = [[UIButton alloc] init];
        _maskButton.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.05f];
        __weak typeof(self) weak_self = self;
        [_maskButton setActionBlock:^(UIControl *control) {
            weak_self.maskButton.enabled = NO;
            [weak_self dismissAnimated:YES];
        } delayDuration:1.0f delayBlock:^(UIControl *control) {
            weak_self.maskButton.enabled = YES;
        }];
    }
    return (_maskButton);
}

- (UITableView *)tableView {
    if(!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:UIEdgeInsetsInsetRect(self.bounds, self.contentInsets)];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = [UIColor clearColor];
        [_tableView registerClass:[ZallFilterViewCell class] forCellReuseIdentifier:CellReuseIdentifier];
        _tableView.rowHeight = 40.0f;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return (_tableView);
}
#pragma mark -

#pragma mark - private

#pragma mark -

#pragma mark - public
- (void)showInView:(UIView * _Nullable)view {
    if(!view || ![view isKindOfClass:[UIView class]]) {
        view = [[UIApplication sharedApplication] keyWindow];
    }
    CGRect fromRect = CGRectMake(0, - self.height, view.width, self.height);
    [self showInView:view fromRect:fromRect animated:YES];
}

- (void)showInView:(UIView * _Nullable)view fromRect:(CGRect)fromRect animated:(BOOL)animated {
    if(!view || ![view isKindOfClass:[UIView class]]) {
        view = [[UIApplication sharedApplication] keyWindow];
    }
    CGRect toRect = CGRectMake(0, 0, self.width, self.height);
    [self showInView:view fromRect:fromRect toRect:toRect animated:animated];
}

- (void)showInView:(UIView * _Nullable)view fromRect:(CGRect)fromRect toRect:(CGRect)toRect animated:(BOOL)animated {
    if(!view || ![view isKindOfClass:[UIView class]]) {
        view = [[UIApplication sharedApplication] keyWindow];
    }
    self.maskButton.frame = view.bounds;
    self.maskButton.alpha = 0.0f;
    if(!self.maskButton.superview) {
        [view addSubview:self.maskButton];
    }
    if(!self.superview) {
        [view addSubview:self];
    }
    self.frame = _fromRect = fromRect;
    [self.tableView reloadData];
    [UIView animateWithDuration:(animated ? ZallFilterAnimationDuration : 0) animations:^{
        self.maskButton.alpha = 1.0f;
        self.frame = toRect;
    }];
}

- (void)dismiss {
    [self dismissAnimated:YES];
}

- (void)dismissAnimated:(BOOL)animated {
    [UIView animateWithDuration:(animated ? ZallFilterAnimationDuration : 0) animations:^{
        self.maskButton.alpha = 0.0f;
        self.frame = _fromRect;
    } completion:^(BOOL finished) {
        if(finished) {
            if(self.maskButton.superview) {
                [self.maskButton removeFromSuperview];
            }
            if(self.superview) {
                [self removeFromSuperview];
            }
        }
    }];
}
#pragma mark -

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ([self.items count]);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZallFilterViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellReuseIdentifier];
    cell.item = [self.items safeObjectAtIndex:indexPath.row];
    return (cell);
}
#pragma mark -

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(self.delegate && [self.delegate respondsToSelector:@selector(filterView:shouldSelectRowAtIndex:)] && ![self.delegate filterView:self shouldSelectRowAtIndex:indexPath.row]) {
        return;
    }
    for(NSInteger index = 0; index < [self.items count]; index ++) {
        ZallFilterItem *item = self.items[index];
        item.selected = (indexPath.row == index);
    }
    if(self.delegate && [self.delegate respondsToSelector:@selector(filterView:didSelectedRowAtIndex:)]) {
        [self.delegate filterView:self didSelectedRowAtIndex:indexPath.row];
    }
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [tableView endUpdates];
}
#pragma mark -

@end



@interface ZallFilterViewCell ()
@end

@implementation ZallFilterViewCell

#pragma mark - life cycle
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self) {
        self.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:self.textLabel];
    }
    return (self);
}
#pragma mark -

#pragma mark - setter
- (void)setItem:(ZallFilterItem *)item {
    [self willChangeValueForKey:@"item"];
    _item = [item copy];
    [self didChangeValueForKey:@"item"];
    if(!_item) {
        return;
    }
    self.showTopLine = _item.showTopLine;
    self.showBottomLine = _item.showBottomLine;
    if(_item.image) {
        self.imageView.size = _item.imageSize;
        self.imageView.image = _item.image;
    }
    if(_item.imageURLString) {
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:_item.imageURLString] placeholderImage:_item.placeholderImage];
    }
    if(_item.text) {
        self.textLabel.attributedText = _item.text;
    }
    if(_item.detailText) {
        self.detailTextLabel.attributedText = _item.detailText;
    }
    if([_item isSelected]) {
        self.checkBoxSize = _item.checkBoxSize;
        self.checkBox.selected = [_item isSelected];
    }
    self.textLabel.attributedText = _item.text;
    [self setNeedsLayout];
}
#pragma mark -

@end



@implementation ZallFilterItem
+ (instancetype)itemWithAttributedText:(NSAttributedString *)attributedText {
    return ([self itemWithAttributedText:attributedText selected:NO]);
}

+ (instancetype)itemWithAttributedText:(NSAttributedString *)attributedText selected:(BOOL)selected {
    ZallFilterItem *item = [[self alloc] init];
    item.text = attributedText;
    item.selected = selected;
    return (item);
}

- (instancetype)init {
    self = [super init];
    if(self) {
        self.showTopLine = NO;
        self.showBottomLine = YES;
        _checkBoxSize = CGSizeZero;
    }
    return (self);
}
@end
